package com.acme.service.bank;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;

public class BankDataLoader {
	private BankService bankService;

	/**
	 * Loads a file which contains data feed in the following format: <br>
	 * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
	 * 
	 * @param bank
	 * @param path
	 * @throws IOException
	 */
	public void load(final Bank bank, final String path) throws IOException {

		// TODO: implement this method parsing a file whose path is passed to
		// the method. Add data to the bank
		System.out.println("Start loading bank from file: " + path);
		FileReader fr = new FileReader(path);
		BufferedReader br = new BufferedReader(fr);
		String record;

		while ((record = br.readLine()) != null) {
			System.out.println("New account : " + record);
			Client client = null;
			Account account = null;
			String accounttype=null;
			
			try {
				String name = parseProperty(record, "name");
				Gender gender = parseProperty(record, "gender").equals("f") ? Gender.FEMALE
						: Gender.MALE;
				client = bankService.addClient(bank, name, gender);
				System.out.print("Add client to bank: ");
				System.out.print(" name="+name);
				System.out.println(" gender="+gender);				
			} catch (ClientExistsException e) {
				System.out.println("Error: client exists, skip creation");
			}

			double balance = Double
					.parseDouble(parseProperty(record, "balance"));
			accounttype = parseProperty(record, "accounttype");

			double overdraft=0;
			if (accounttype.equals("c")) {
				overdraft = Double.valueOf(parseProperty(record,
						"overdraft"));
				account = new CheckingAccount(2, balance, overdraft);
			} else if (accounttype.equals("s")) {
				account = new SavingAccount(2, balance);
			}
			client.addAccount(account);
			System.out.print("Add account to client: ");
			System.out.print(" accounttype="+accounttype);
			System.out.print(" overdraft="+overdraft);
			System.out.println(" balance="+balance);

			System.out.println(bank);
		}

		br.close();
		fr.close();
	}

	private String parseProperty(String row, String key) {
		Pattern pattern = Pattern.compile(key + "=([^;]*)");
		Matcher matcher = pattern.matcher(row);
		matcher.find();
		return matcher.group(1);
	}

	public BankService getBankService() {
		return bankService;
	}

	public void setBankService(final BankService bankService) {
		this.bankService = bankService;
	}
}
